<template>
  <div class="common-container">
    <div class="common-content">
      <div class="order-confirm-wrapper">
        <h2 class="page-title">确认订单</h2>

        <el-card class="order-card">
          <!-- 收货地址 -->
          <div class="section">
            <h3 class="section-title">收货信息</h3>
            <div v-if="addresses.length > 0" class="address-list">
              <div v-for="address in addresses" :key="address.id" class="address-item" 
                :class="{ 'active': selectedAddressId === address.id }" @click="selectAddress(address.id)">
                <div class="address-header">
                  <span class="address-name">{{ address.name }}</span>
                  <span class="address-phone">{{ address.phone }}</span>
                  <el-radio v-model="selectedAddressId" :label="address.id" :border="false" 
                    class="address-radio"></el-radio>
                </div>
                <div class="address-content">
                  {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detail }}
                </div>
              </div>
            </div>
            <div v-else class="no-address">
              <el-empty description="暂无收货地址" style="margin: 20px 0"></el-empty>
              <el-button type="primary" @click="addAddress">添加收货地址</el-button>
            </div>
          </div>

          <!-- 商品信息 -->
          <div class="section">
            <h3 class="section-title">商品信息</h3>
            <el-table :data="orderItems" style="width: 100%" border>
              <el-table-column prop="productName" label="商品名称" min-width="200" align="center">
                <template slot-scope="scope">
                  <div class="goods-info-cell">
                    <img :src="scope.row.goodsImg" alt="" class="goods-small-img">
                    <span>{{ scope.row.goodsName }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="单价" width="100" align="center">
                <template slot-scope="scope">
                  ¥{{ scope.row.price }}
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100" align="center"></el-table-column>
              <el-table-column label="小计" width="100" align="center">
                <template slot-scope="scope">
                  <span class="subtotal">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 订单金额 -->
          <div class="section">
            <h3 class="section-title">订单金额</h3>
            <div class="order-amount">
              <div class="amount-item">
                <span>商品总价:</span>
                <span>¥{{ totalPrice.toFixed(2) }}</span>
              </div>
              <div class="amount-item">
                <span>运费:</span>
                <span>¥0.00</span>
              </div>
              <div class="amount-item total">
                <span>实付金额:</span>
                <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
              </div>
            </div>
          </div>

          <!-- 备注 -->
          <div class="section">
            <h3 class="section-title">订单备注</h3>
            <el-input type="textarea" v-model="remark" placeholder="选填，填写其他需求"></el-input>
          </div>

          <!-- 提交订单 -->
          <div class="order-footer">
            <div class="order-summary">
              <span>共 {{ totalQuantity }} 件商品，合计:</span>
              <span class="final-price">¥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <el-button type="primary" size="large" @click="submitOrder" :disabled="!selectedAddressId || loading">
              <span v-if="loading"><i class="el-icon-loading"></i> 提交中...</span>
              <span v-else>提交订单</span>
            </el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "OrderConfirm",
  data() {
    return {
      orderItems: [],
      addresses: [],
      selectedAddressId: '',
      remark: '',
      loading: false,
      // 从URL获取的参数
      goodsId: '',
      quantity: 1,
      cartItemIds: ''
    };
  },
  computed: {
    // 计算总价格
    totalPrice() {
      return this.orderItems.reduce((total, item) => {
        return total + (item.price * item.quantity);
      }, 0);
    },

    // 计算商品总数
    totalQuantity() {
      return this.orderItems.reduce((total, item) => {
        return total + item.quantity;
      }, 0);
    }
  },
  created() {
    // 获取URL参数
    this.goodsId = this.$route.query.goodsId || this.$route.query.productId; // 兼容旧参数
    this.quantity = parseInt(this.$route.query.quantity) || 1;
    this.cartItemIds = this.$route.query.cartItemIds;

    this.loadOrderItems();
    this.loadAddresses();
  },
  methods: {
    loadOrderItems() {
      if (this.goodsId) {
        // 从立即购买进入
        this.request.get(`/goods/${this.goodsId}`).then(res => {
          if (res.code === 200 && res.data) {
            const goods = res.data;
            this.orderItems = [{
              goodsId: goods.id,
              goodsName: goods.goodsName || goods.name,
              goodsImg: goods.imgUrl || goods.img,
              price: goods.price,
              quantity: this.quantity
            }];
          }
        }).catch(error => {
          console.error('加载商品信息失败:', error);
          this.$message.error('加载商品信息失败');
        });
      } else if (this.cartItemIds) {
        // 从购物车结算进入
        this.request.get(`/cart/page`, {
          params: {
            ids: this.cartItemIds,
            pageNum: 1,
            pageSize: 100
          }
        }).then(res => {
          if (res.code === 200 && res.data && res.data.records) {
            this.orderItems = res.data.records.map(item => ({
              goodsId: item.goodsId || item.productId,
              goodsName: item.goodsName || item.productName,
              goodsImg: item.imgUrl || item.productImg,
              price: item.price,
              quantity: item.num || item.quantity,
              cartItemId: item.id
            }));
          }
        }).catch(error => {
          console.error('加载购物车商品失败:', error);
          this.$message.error('加载购物车商品失败');
        });
      }
    },

    loadAddresses() {
      this.request.get("/address").then(res => {
        if (res.code === 200) {
          this.addresses = res.data || [];
          if (this.addresses.length > 0) {
            this.selectedAddressId = this.addresses[0].id;
          }
        }
      }).catch(error => {
        console.error('加载地址信息失败:', error);
        this.$message.error('加载地址信息失败');
      });
    },

    selectAddress(addressId) {
      this.selectedAddressId = addressId;
    },

    addAddress() {
      // 这里可以跳转到添加地址页面，或者显示添加地址的弹窗
      this.$message.info('添加地址功能待实现');
    },

    submitOrder() {
      if (!this.selectedAddressId) {
        this.$message.warning('请选择收货地址');
        return;
      }

      if (this.orderItems.length === 0) {
        this.$message.warning('订单中没有商品');
        return;
      }

      this.loading = true;

      const orderData = {
        addressId: this.selectedAddressId,
        remark: this.remark,
        totalPrice: this.totalPrice,
        orderItems: this.orderItems.map(item => ({
          goodsId: item.productId,
          num: item.quantity,
          price: item.price,
          cartItemId: item.cartItemId
        }))
      };

      this.request.post("/orders", orderData).then(res => {
        this.loading = false;

        if (res.code === 200 && res.data) {
          // 订单创建成功，跳转到支付页面
          this.$message.success('订单创建成功');
          this.$router.push({
            path: '/front/orderDetail',
            query: {
              orderId: res.data
            }
          });
        } else {
          this.$message.error(res.msg || '订单创建失败');
        }
      }).catch(error => {
        this.loading = false;
        console.error('提交订单失败:', error);
        this.$message.error('订单创建失败');
      });
    }
  }
};
</script>

<style scoped>
.common-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.common-content {
  margin-bottom: 20px;
}

.order-confirm-wrapper {
  width: 100%;
}

.page-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #303133;
  font-weight: 500;
}

.order-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.section {
  margin-bottom: 30px;
  padding: 0 20px;
}

.section:nth-child(1) {
  padding-top: 20px;
}

.section-title {
  font-size: 16px;
  margin-bottom: 15px;
  color: #303133;
  font-weight: 500;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.section:nth-child(1) .section-title {
  border-top: none;
  padding-top: 0;
}

.address-list {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.address-item {
  border: 2px solid #e4e7ed;
  padding: 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 300px;
  position: relative;
}

.address-item:hover {
  border-color: #c0c4cc;
}

.address-item.active {
  border-color: #409eff;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.address-name {
  margin-right: 20px;
  color: #303133;
}

.address-phone {
  color: #606266;
  margin-right: auto;
}

.address-radio {
  position: absolute;
  right: 15px;
  top: 15px;
}

.address-content {
  color: #606266;
  line-height: 1.5;
}

.no-address {
  padding: 40px 0;
  text-align: center;
}

.goods-info-cell {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.goods-small-img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  margin-right: 10px;
}

.subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.order-amount {
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #606266;
}

.amount-item.total {
  font-weight: bold;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #e4e7ed;
}

.total-price {
  color: #f56c6c;
  font-size: 18px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
  margin-top: 20px;
}

.order-summary {
  display: flex;
  align-items: center;
}

.final-price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
  margin-left: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .common-container {
    padding: 10px;
  }
  
  .section {
    padding: 0 15px;
  }
  
  .address-item {
    min-width: 100%;
  }
  
  .order-footer {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .order-summary {
    justify-content: center;
  }
}
</style>